package zhh.tangbao.machine.socket.client;

import zhh.tangbao.commodity.constant.MachineRunningState;
import zhh.tangbao.commodity.dao.CommodityMachineEntityDao;
import zhh.tangbao.machine.pojo.PreConnectionVerificationMachine;
import zhh.tangbao.machine.socket.handler.MachineSocketDisconnectHandler;
import zhh.tangbao.system.utils.ApplicationContextUtil;

import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * <p>
 *     机器socket客户端
 * </p>
 * @author 粥灰灰
 * <p>2023/3/25</p>
 */
public class MachineSocketClient {

    private PreConnectionVerificationMachine machine;

    private Socket client;

    private Timer timer;

    private MachineSocketDisconnectHandler handler;

    class MachineSocketClientTask extends TimerTask {

        @Override
        public void run() {
            try {
                client.getOutputStream().write(1);
            } catch (IOException e) {
                if ( e instanceof SocketException) {
                    CommodityMachineEntityDao dao = ApplicationContextUtil.getBean(CommodityMachineEntityDao.class);
                    dao.updateMachineRunningState(machine.getMachineId(), MachineRunningState.CLOSE);
                    // 消息发送失败意味着socket断开，所以应该向系统全局发送该机器服务停止运行的信息
                    timer.cancel();
                    handler.disconnectWarning(machine, new Date());
                } else {
                    e.printStackTrace();
                }
            }
        }
    }

    public MachineSocketClient() {
    }

    public MachineSocketClient(PreConnectionVerificationMachine machine, Socket client, Timer timer, MachineSocketDisconnectHandler handler) {
        this.machine = machine;
        this.client = client;
        this.timer = timer;
        this.handler = handler;
    }

    public String getMachineId() {
        return machine.getMachineId();
    }

    public Socket getClient() {
        return client;
    }

    public Timer getTimer() {
        return timer;
    }

    public void schedule(long timeInterval) {
        this.timer.schedule(new MachineSocketClientTask(), timeInterval, timeInterval);
    }
}
